/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.controller;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.result.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.core.oss.domain.FileStatus;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.vo.OssFileVo;

import java.util.List;

@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor
public class OssController {

    private final OSS oss;

    //    上传文件操作
    @PostMapping("/upload")
    public R<OssFileVo> uploadFile(@RequestParam("file") MultipartFile file,
                                   @RequestParam("userId") Integer userId,
                                   @RequestParam("subject") String subject) {

        List<OssFile> ossFiles = oss.saveFile(subject, userId + "", file);

        //        把返回的文件列表返回给前端去渲染
        return R.success(BeanUtil.copyProperties(ossFiles.get(0), OssFileVo.class));
    }

    @PostMapping("/upload/large")
    public R<OssFileVo> uploadBigFile(@RequestParam("file") MultipartFile file,
                                      @RequestParam("hash") String hash,
                                      @RequestParam("chunkHash") String chunkHash,
                                      @RequestParam("userId") Integer userId,
                                      @RequestParam("index") Integer index,
                                      @RequestParam("subject") String subject,
                                      @RequestParam("fileName") String fileName) {

        if (chunkHash.equals("end")) {

            OssFile ossFile = oss.saveBigFile(userId + "", hash, subject, fileName);

            return R.success(BeanUtil.copyProperties(ossFile, OssFileVo.class));
        } else {
            Integer i = oss.saveBigFile(file, userId + "", hash, index + "", chunkHash);

            return i == 1 ? R.success() : R.fail("上传失败");
        }

    }

    @GetMapping("/status")
    public R<FileStatus> getFileStatus(@RequestParam("hash") String hash, @RequestParam("userId") Integer user) {
        FileStatus fileStatus = oss.getFileStatus(hash, user);
        return R.success(fileStatus);
    }

}
